<?php
declare(strict_types=1);

namespace SixShop\System\Trait;

use SixShop\System\ExtensionManager;

trait ConfigTrait
{
    public function __construct(private readonly ExtensionManager $extensionManager, private array $options = [])
    {
    }

    public function getConfig(string $key = null, mixed $default = null): mixed
    {
        if (empty($this->options)) {
            if (!method_exists($this, 'getExtensionID')) {
                return [];
            }
            $this->options = $this->extensionManager->getExtensionConfig($this->getExtensionID());
            if (method_exists($this, 'getOptions')) {
                $this->options = array_merge($this->options, $this->getOptions());
            }
        }
        return $key ? ($this->options[$key] ?? $default) : $this->options;
    }

    public function __get(string $name): mixed
    {
        return $this->getConfig($name);
    }

    public function __isset(string $name): bool
    {
        return $this->getConfig($name) !== null;
    }

    public function __call(string $name, array $arguments): mixed
    {
        if (str_starts_with($name, 'get')) {
            $name = lcfirst(substr($name, 3));
        } else {
            throw new \BadMethodCallException("Method {$name} does not exist.");
        }
        $name = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $name));
        return $this->getConfig($name);
    }
}